using CloudStorageLight.Core;
using CloudStorageLight.Core.Web;
using CloudStorageLight.SharePointWeb.Models;
using Microsoft.SharePoint.Client;
using System;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Linq;
using System.Diagnostics.CodeAnalysis;

namespace CloudStorageLight.SharePointWeb
{
    /// <summary>
    /// SharePoint の操作のフィルター属性。
    /// </summary>
    [ExcludeFromCodeCoverage]
    public class SharePointContextFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (AttachedSharePointBlobAdapter.GetSpsClientContext() != null && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) return;


            Uri redirectUrl;
            var result = SharePointContextProvider.CheckRedirectionStatus(filterContext.HttpContext, out redirectUrl);
            var log = new LogService(SystemSettings.Instance.BlobStorage);
            switch (result)
            {
                case RedirectionStatus.Ok:
                    var ctx = SharePointContextProvider.Current.GetSharePointContext(filterContext.HttpContext);
                    if (ctx != null)
                    {
                        //SharePointで認証
                        var client = ctx.CreateUserClientContextForSPHost();
                        if (client != null)
                        {
                            AttachedSharePointBlobAdapter.SetSpsClientContext(client);

                            var spUser = client.Web.CurrentUser;
                            client.Load(spUser, x => x.Email, x => x.Groups);
                            client.ExecuteQuery();
                            var email = string.IsNullOrEmpty(spUser.Email) ? "GUEST" : spUser.Email;
                            var u = new AppBlobUser(new GenericPrincipal(new GenericIdentity(email), null));
                            if (string.IsNullOrEmpty(spUser.Email))
                            {
                                u.IsGuest = true;
                            }
                            var account = BlobService.GetCurrentCloudAccount();
                            if (account == null)
                            {
                                account = CloudAccount.LoadBySpHostUrl(SystemSettings.Instance.BlobStorage, ctx.SPHostUrl.AbsoluteUri);
                                if (account == null) throw new BlobException(ViewMessages.MsgNotFoundCloudAccount);
                            }

                            var ticket = new FormsAuthenticationTicket(0, spUser.Email, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(account.AuthTicketTimeout.Value), false, account.AccountName);
                            HttpCookie cookie = new HttpCookie(
                                FormsAuthentication.FormsCookieName,
                                FormsAuthentication.Encrypt(ticket));
                            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                            System.Web.HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(spUser.Email), spUser.Groups.Select(x => x.Title).ToArray());

                        }
                    }
                    return;
                case RedirectionStatus.ShouldRedirect:
                    filterContext.Result = new RedirectResult(redirectUrl.AbsoluteUri);
                    break;
                case RedirectionStatus.CanNotRedirect:
                    break;
            }

        }
    }
}
